import { defineStore } from 'pinia'
import { userKey } from './keys'
import router from '@/router'
interface IUserState {
  menus: IMenu[]
  username: string
}

type menu = IMenu & { children: IMenu[] }

export const useUserStore = defineStore(userKey, {
  state(): IUserState {
    return {
      menus: [],
      username: ''
    }
  },
  getters: {
    routerMenu() {
      let menus: menu[] = []
      // 找到所有一级菜单
      menus = this.menus
        .filter((item) => item.parentId === 0)
        .map((item) => ({
          ...item,
          children: [],
        }))

      // 找二级菜单
      this.menus.forEach((item) => {
        // 找到1级跟二级相同的id
        const temp = menus.find((sub) => sub.id === item.parentId)

        // 如果找到1级，加入children列表
        // if (temp && item.hidden === 0) {
        //   temp.children.push(item)
        // }
        if (temp) {
          temp.children.push(item)
        }
      })

      return menus
    },
    permission(): string[] {
      return this.menus.map(item => item.name)
    }
  },
  actions: {
    logOut() {
      localStorage.removeItem('token')
      // const router = useRouter()
      // 清除动态路由
      this.menus
        .filter((item) => item.parentId === 0)
        .forEach((item) => {
          router.removeRoute(item.name)
        })

      this.menus = []
      this.username = ''

    }
  }

})
